#!/usr/bin/python
# -*-coding: UTF-8 -*-
"""
# Time: 2021/11/14 11:06
# @Author: 修养
# @Project_name: PROJECT_NAME
"""
# 1、读取整个文件
with open('test_file/read.txt', encoding='utf-8') as file:
    contents = file.read()
print('输出全部内容：', contents)
# 2、逐行读取
file_path = 'test_file/read2.txt'
with open(file_path, encoding='utf-8') as file:
    for line in file:
        print(line.rstrip())
# 3、创建一个包含文件各行内容的列表
with open(file_path, encoding='utf-8') as file:
    lines = file.readlines()
print('列表：', lines)

# （'r'）、('w')、（'r+'）、（'a'）
print('~~~~~~~~~~~~2、向文件中写数据~~~~~~~~~~~~')
# 1、写入多行
with open('test_file/write1.txt', mode='w') as file:
    file.write('Hello World!')
# 2、写入多行
with open('test_file/write2.txt', mode='w') as file:
    file.write('Hello World!\n')
    file.write('Hello World!\n')
# 3、追加文件
with open(file='test_file/write2.txt', mode='a', encoding='utf-8') as file:
    file.write('追加： Hello World!\n')
    file.write('追加： Hello World!\n')

print('~~~~~~~~~~~~~3、使用try-except代码块~~~~~~~~~~~~~')

try:
    a = 5 / 0
except ZeroDivisionError:
    print('除数不能为0！')
else:
    print('输出a =', a)
try:
    with open('test_file/try_write.txt', mode='w', encoding='utf-8') as f:
        # lines = f.read()          # 文件不存在时，抛出异常
        f.write('try-except代码块！')  # 文件不存在时，自动创建
except FileNotFoundError:
    pass
else:
    print('文件写入成功！')

